/**
 *
 */
package com.yangtao.prototype.system.dao;

import com.yangtao.framework.hibernate.BaseDao;
import com.yangtao.prototype.system.domain.Role;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.stereotype.Repository;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 杨涛
 */
@Repository
public class RoleDao extends BaseDao<Role> {

	public void deleteAuthorityByRole(String roleId) {
		//1 删除已有的功能权限（中间表）
		String sql = "delete from FunctionAuthority a where a.role.id=?";
		batchExecute(sql, roleId);
		//TODO 2 删除页面权限
	}

	/**
	 * 增加自定义的筛选条件
	 *
	 * @param criteria
	 */
	protected void addCustomCriterion(Criteria criteria, Object... parameters) {
		if (parameters != null && parameters.length > 0) {
			if (parameters[0] != null) {
				//增加数据权限的约束原生sql的约束
				String organizePath = parameters[0].toString();
				criteria.add(Restrictions.sqlRestriction("exists (select 1 from sys_organization org where org.id = {alias}.organizationId and org.path like ?)",
						organizePath + "%", StandardBasicTypes.STRING));
			}
		}
	}

	/**
	 * 根据主键查询(用于将对象持久化)
	 *
	 * @param id 主键
	 * @return 持久化对象
	 */
	public Role load(String id) {
		Role role = super.load(id);
		getHibernateTemplate().initialize(role.getFunctionAuthorize());
		getHibernateTemplate().initialize(role.getUsers());
		return role;
	}

	public Set<String> loadAuthorizedMenu(String roleId) {
		HashSet<String> set = new HashSet<String>();
		if (StringUtils.isNotEmpty(roleId)) {
			String sql = "select mt.id from MenuTree mt,FunctionAuthority fa where fa.menu=mt and fa.role.id=?";
			List<String> checked = find(sql, roleId);
			set.addAll(checked);
		}
		return set;
	}
}
